package com.lyc.api;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyc.constants.Constants;
import com.lyc.utils.HttpClient;
import com.lyc.utils.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 优量汇广告客户端API。
 */
public class YlhApiClient {

    private static final Gson policyGson = new Gson();

    public static int YLH_APP_ID;
    public static long YLH_MEMBER_ID;
    public static String YLH_SECRET;

    static {
        loadProperties();
    }

    private static void loadProperties() {
        Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream(new File(Constants.ACCOUNT_PATH + "account.properties"))) {
            props.load(fis);

            YLH_APP_ID = Integer.parseInt(props.getProperty("YLH_APP_ID"));
            YLH_MEMBER_ID = Long.parseLong(props.getProperty("YLH_MEMBER_ID"));
            YLH_SECRET = String.valueOf(props.getProperty("YLH_SECRET"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建优量汇横幅广告。
     *
     * @return 创建的广告ID
     */
    public static long createYlhBannerAd() {
        Map<String, Object> specificParams = new HashMap<>();
        specificParams.put("render_type", "TEMPLATE");
        specificParams.put("ad_crt_type_list", new String[]{"IMAGE"});
        specificParams.put("ad_crt_template_type", new String[]{"BANNER_DP"});
        specificParams.put("price_strategy_type", "BiddingPrice");
        specificParams.put("real_time_bidding_type", "Server_Bidding");
        specificParams.put("custom_position_scene_level3", "FOCUS_POINT_OTHER");

        return createYlhAd("优量汇_横幅_rv", specificParams);
    }

    /**
     * 创建优量汇信息流广告。
     *
     * @return 创建的广告ID
     */
    public static long createYlhNativeAd() {
        Map<String, Object> specificParams = new HashMap<>();
        specificParams.put("render_type", "TEMPLATE");
        specificParams.put("ad_crt_type_list", new String[]{"VIDEO", "IMAGE"});
        specificParams.put("ad_crt_template_type", new String[]{"TP_BT", "TT_BP", "LP_RT", "RP_LT", "DB_TI", "V_IMG", "H_IMG", "THR_IMG", "TT_BP_MASK", "TP_BT_MASK", "TP_IMG_MASK"});
        specificParams.put("price_strategy_type", "BiddingPrice");
        specificParams.put("real_time_bidding_type", "Server_Bidding");
        specificParams.put("custom_position_scene_level3", "FLOW_NORMAL_1");

        return createYlhAd("优量汇_信息流_rv", specificParams);
    }

    /**
     * 创建优量汇半屏插屏广告。
     *
     * @return 创建的广告ID
     */
    public static long createYlhHalfScreenInsertAd() {
        Map<String, Object> specificParams = new HashMap<>();
        specificParams.put("render_type", "TEMPLATE");
        specificParams.put("ad_crt_type_list", new String[]{"VIDEO", "IMAGE"});
        specificParams.put("ad_crt_template_type", new String[]{"INLINE_VHS"});
        specificParams.put("price_strategy_type", "BiddingPrice");
        specificParams.put("real_time_bidding_type", "Server_Bidding");
        specificParams.put("custom_position_scene_level3", "INSERTION_INSERTION");

        return createYlhAd("优量汇_弹窗_rv", specificParams);
    }

    /**
     * 创建优量汇激励视频广告。
     *
     * @return 创建的广告ID
     */
    public static long createYlhRewardAd() {
        Map<String, Object> specificParams = new HashMap<>();
        specificParams.put("rewarded_video_crt_type", "ALL_DIRECTION");
        specificParams.put("need_server_verify", "NeedServerVerify");
        specificParams.put("transfer_url", "http://quanminchangwan.kuhuanqiye.top/api/huitiao.houtai/youliang");
        specificParams.put("secret", StringUtil.generateRandomString(32));
        specificParams.put("price_strategy_type", "BiddingPrice");
        specificParams.put("real_time_bidding_type", "Server_Bidding");
        specificParams.put("custom_position_scene_level3", "REWARDED_APP_OTHER");

        return createYlhAd("优量汇_激励_rv", specificParams);
    }

    /**
     * 创建优量汇开屏广告。
     *
     * @return 创建的广告ID
     */
    public static long createYlhSplashAd() {
        Map<String, Object> specificParams = new HashMap<>();
        specificParams.put("flash_crt_type", "FLASH");
        specificParams.put("price_strategy_type", "BiddingPrice");
        specificParams.put("real_time_bidding_type", "Server_Bidding");
        specificParams.put("custom_position_scene_level3", "FLASH_OTHER");

        return createYlhAd("优量汇_开屏_rv", specificParams);
    }

    /**
     * 创建优量汇广告的通用方法。
     *
     * @param placementName 广告位名称
     * @param specificParams 特定参数
     * @return 创建的广告ID
     */
    private static long createYlhAd(String placementName, Map<String, Object> specificParams) {
        String url = "https://api.adnet.qq.com/open/v1.1/placement/add";

        Map<String, Object> params = new HashMap<>();
        params.put("member_id", YLH_MEMBER_ID);
        params.put("app_id", YLH_APP_ID);
        params.put("placement_name", placementName + "_" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        params.put("ad_pull_mode", "SDK");

        params.putAll(specificParams);

        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");

        String response = HttpClient.doPost(url, params, headers);
        System.out.println("response = " + response);

        return parseResponse(response);
    }

    /**
     * 解析HTTP响应数据。
     *
     * @param response HTTP响应字符串
     * @return 创建的广告ID或-1表示失败
     */
    private static long parseResponse(String response) {
        Type responseType = new TypeToken<Map<String, Object>>() {}.getType();
        Map<String, Object> responseMap = policyGson.fromJson(response, responseType);

        int code = ((Number) responseMap.get("code")).intValue();
        if (code == 0) {
            Map<String, Object> placementMap = (Map<String, Object>) responseMap.get("data");
            long placementId = ((Number) placementMap.get("placement_id")).longValue();
            return placementId;
        } else {
            System.out.println("Failed to create placement. Code: " + code);
            return -1;
        }
    }

    /**
     * 获取请求头。
     *
     * @return 请求头Map
     */
    private static Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("token", generateToken());
        return headers;
    }

    /**
     * 生成Token。
     *
     * @return Token字符串
     */
    private static String generateToken() {
        long timeStamp = System.currentTimeMillis() / 1000;
        String sign = DigestUtils.sha1Hex(YLH_MEMBER_ID + YLH_SECRET + timeStamp);
        String tokenString = String.join(",", Long.toString(YLH_MEMBER_ID), Long.toString(timeStamp), sign);
        return Base64.getEncoder().encodeToString(tokenString.getBytes(StandardCharsets.UTF_8));
    }
}
